// pages/authorizedPage/authorizedPage.js
import {
  ApiRootUrl,
  apiList
} from '../../config/index.js'
import Toast from '../../@vant/weapp/toast/toast';
import Dialog from '../../@vant/weapp/dialog/dialog';
import {
  IMG_PATH
} from '../../config/index.js'
import {request,login} from "../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tishiShow:false,
    message:'',
    chooseMulitUser:false,
    columnsUser:[],
    result:0,
    user:{},
    showUserList:false,
    userList:[]
  },
  isCanbaoConfirm(e){
    let self=this
    console.log(e);
    this.newLogin1(e.detail.value)
    
  },
  isCanbaoCancel(){
    let self=this
    this.setData({
      showUserList:false
    })
    wx.showModal({
      title: '提示',
      content: '您已注册过心园通小程序,请选择角色登录?',
      cancelText:"选择角色",
      confirmText:"确定",
      success (res) {
        if (res.confirm) {
          self.setData({
            showUserList:true
          })
        } else if (res.cancel) {
          self.setData({
            showUserList:true
          })
        }
      }
    })
  },
  closeUserList(){
    let self=this
    this.setData({
      showUserList:false
    })
    wx.showModal({
      title: '提示',
      content: '您已注册过心园通小程序,请选择角色登录?',
      cancelText:"选择角色",
      confirmText:"确定",
      success (res) {
        if (res.confirm) {
          self.setData({
            showUserList:true
          })
        } else if (res.cancel) {
          self.setData({
            showUserList:true
          })
        }
      }
    })
  },
  onChangeLabel(event) {
    let index = Number(event.detail)
    console.log("this.data.columnsUser[index]=>",this.data.columnsUser[index])
    this.setData({
      result: event.detail,
      user:this.data.columnsUser[index]
    });
   
  },
  onChangeUser(event){
    const { picker, value, index } = event.detail;
  },
  onConfirmUser(event){
    // const { picker, value, index } = event.detail;
    let value = this.data.user
    console.log(value)
    if(this.data.user == undefined ){
      Toast("请选择用户")
      return
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.doLoginAppManagerUser+`?openId=${value.openId}&labourCode=${value.laobourCode == null ? "":value.laobourCode}&componentCode=${value.componentCode==null ? "":value.componentCode}&userType=${value.userType}`,
    {},"GET").then(res =>{
      Toast.clear();
      console.log(res)
      let data1 = res.data
      wx.setStorageSync('userinfo', data1)
      // 无user表示是劳务工
      if (!data1.user) {
        let type  = 0;
        if(data1.labourCode == null){
          type = 1
        }
        wx.redirectTo({
          url: '/pages/firstpage/firstpage?componentType='+type,
        })
      } else {
        console.log("data.user===>", data1.user)
        // 有user表示是非劳务工
        if (data1.user.typeCode == 'business') {
          wx.redirectTo({
            url: '../companyfirstpage/companyfirstpage',
          })
        } else if (data1.user.typeCode == 'labour') {
          wx.redirectTo({
            url: '../laborcompany/firstpage/firstpage',
          })
        }
        else if (data1.user.typeCode == 'society') {
          wx.redirectTo({
            url: '/pages/laborcompany/firstpage/firstpage'
          });
        }
      }
    }).catch(err =>{
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
    return
    this.setData({
      chooseMulitUser:false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   * 
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
    })
    let phone = wx.getStorageSync('phoneNumber')
    let openId = wx.getStorageSync('openId')
    login().then(_=>{
      this.checkRegister()
    })
    // this.setData({
    //   chooseMulitUser:true
    // })
  },
  toDetaily(){
    wx.navigateTo({
      url: '../authorizedInfo/authorizedInfo',
    })
  },
  onCloseUserPopup(){
    this.setData({
      chooseMulitUser:false
    })
  },
  getPhoneNumber(e) {
    let self = this;
    let flag = true;
    wx.checkSession({
      success: function (res) {
        console.log('session_key未过期')
        //session_key未过期
        flag = true;
      },
      fail: function (res) {
        flag = false;
        self.setData({
          tishiShow: true
        })
      }
    })
    if (!flag) {
      return;
    }
    let openId = wx.getStorageSync("openId");
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      let url = `${ApiRootUrl}/index/grantPhone`;
      let params = {
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData
      }
      Toast.loading({
        message: '加载中...',
        mask: true,
        duration: 0,
        forbidClick: true,
      });
      wx.request({
        url: url,
        method: 'GET',
        header: {
          'content-type': 'application/json; charset=utf-8',
          'cookie': wx.getStorageSync("sessionid")
        },
        params: params,
        data: params,
        success(res) {
          Toast.clear();
          if (res.data.code == 20000) {
            let phoneNumber = res.data.data;
            wx.setStorageSync("phoneNumber", phoneNumber);
            let openId = wx.getStorageSync('openId')
            // request(apiList.registerVisitor+`?openId=${openId}&phone=${phoneNumber}`,{},"GET").then(res =>{
            //   wx.setStorageSync('userinfo', res.data)
            //   console.log("res=======>",res)
            //   if(res.data.userType == 2){
            //     if(!res.data.user){
            //       let type  = 0;
            //       if(res.data.labourCode == null){
            //         type = 1
            //       }
            //       wx.redirectTo({
            //         url: '/pages/firstpage/firstpage?componentType='+type,
            //       })
                  
            //     }else{
            //       if (res.data.user.typeCode == 'business') {
            //         wx.redirectTo({
            //           url: '/pages/companyfirstpage/companyfirstpage',
            //         })
            //       } else if (res.data.user.typeCode == 'labour') {
            //         wx.redirectTo({
            //           url: '/pages/laborcompany/firstpage/firstpage',
            //         })
            //       }
            //     }
            //   }else if(res.data.userType == 4){
            //     wx.redirectTo({
            //       url: '/pages/firstpage/firstpage?componentType='+10,
            //     })
            //   }  
            //   // wx.redirectTo({
            //   //   url: '/pages/firstpage/firstpage?componentType='+10,
            //   // })
            // }).catch(err =>{
            //   console.log("err=>",err)
            //   wx.showToast({
            //     title:err.message,
            //   })
            // })
            let params1={
              phone:phoneNumber,
              openId:openId,
              componentType:7
            }
            wx.request({
              url: `${ApiRootUrl}/index/newScanVisitorRegister`,
              method: 'POST',
              header: {
                'content-type': 'application/json; charset=utf-8',
                'cookie': wx.getStorageSync("sessionid")
              },
              data:params1,
              success(res) {
                // console.log(res);
                self.newLogin2(res.data.data)
                
              },
              fail(res){
                Toast({
                  duration: 3000,
                  forbidClick: true,
                  type: 'fail',
                  message: '网络已断开',
                });
              }
            })
            
          } else if (res.data.code == 30000) {
            self.setData({
              tishiShow: true
            })
          } else {
            Toast({
              duration: 3000,
              forbidClick: true,
              type: 'fail',
              message: res.data.message,
            });
          }
        },
        fail(res) {
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: '网络已断开',
          });
        }
      })
    } else {
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: '不授权将无法登录该小程序！',
      });
    }
  },
  newLogin1(params){
    Toast.loading({
      duration: 0,
      message: '登录中...',
      forbidClick: true,
    });
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/index/newLogin`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        Toast.clear();
        if(res.data.code == 20000){
         wx.setStorageSync('userinfo', res.data.data)
         let data=res.data.data
    if (!data.user) {
      wx.redirectTo({
        url: `/pages/firstpage/firstpage?isLogin=${0}`,
      })
    }else{
       // 有user表示是非劳务工
       if (data.user.typeCode == 'business') {
        wx.redirectTo({
          url: '/pages/companyfirstpage/companyfirstpage',
        })
      } else if (data.user.typeCode == 'labour') {
        wx.redirectTo({
          url: '/pages/laborcompany/firstpage/firstpage',
        })
      }
    }
        }else{
         
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  newLogin2(params){
    Toast.loading({
      duration: 0,
      message: '登录中...',
      forbidClick: true,
    });
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/index/newLogin`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        Toast.clear();
        if(res.data.code == 20000){
         wx.setStorageSync('userinfo', res.data.data)
         if(res.data.data.userType == 2){
          if(!res.data.data.user){
            let type  = 0;
            if(res.data.data.labourCode == null){
              type = 1
            }
            wx.redirectTo({
              url: '/pages/firstpage/firstpage?componentType='+type,
            })
            
          }else{
            if (res.data.data.user.typeCode == 'business') {
              wx.redirectTo({
                url: '/pages/companyfirstpage/companyfirstpage',
              })
            } else if (res.data.data.user.typeCode == 'labour') {
              wx.redirectTo({
                url: '/pages/laborcompany/firstpage/firstpage',
              })
            }
          }
        }else if(res.data.data.userType == 4){
          wx.redirectTo({
            url: `/pages/firstpage/firstpage?componentType=${7}&isLogin=${0}`
          })
        }  
        }else{
         
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  // checkRegister() {
  //   let self = this;
  //   let openId = wx.getStorageSync("openId");
  //   let url = `${ApiRootUrl}/index/checkAppRegisterUser/${openId}`;
  //   Toast.loading({
  //     message: '加载中...',
  //     mask: true,
  //     duration: 0,
  //     forbidClick: true,
  //   });
  //   wx.request({
  //     url: url,
  //     method: 'GET',
  //     header: {
  //       'content-type': 'application/json; charset=utf-8',
  //       'cookie': wx.getStorageSync("sessionid")
  //     },
  //     success(res){
  //       Toast.clear();
  //       console.log("res====>",res)
  //       if (res.data.code == 20000) {
  //         let data = res.data.data;
  //         console.log("data.user===>", data,data.length )
  //         if(data.length > 1){
  //           let list = []
  //           data.forEach((item,index)=>{
  //             let text = ""
  //             //0待面试务工人员;1在职务工人员;2在职非务工人员;3离职务工人员;4游客;
  //             if(item.userType == 0){
  //               text = "待面试务工人员"
  //             }else if(item.userType == 1){
  //               text = "在职务工人员"
  //             }else if(item.userType == 2){
  //               text = item.user.roleName
  //             }else if(item.userType == 4){
  //               text = "游客"
  //             }else if(item.userType == 3){
  //               text = "离职务工人员"
  //             }
  //             let name = item.componentName == null ? item.labourName:item.componentName
  //             list.push(
  //               {
  //                 openId:item.openId,
  //                 id:index,
                  
  //                 laobourCode:item.labourCode,
  //                 componentCode:item.componentCode,
  //                 componentName:item.componentName,
  //                 text: item.userType == 4 ? "游客" : item.name+'-'+name+"-"+text,
  //                 userType:item.userType
  //               }
  //             )
              
  //           })
  //           console.log(list)
  //           self.setData({
  //             chooseMulitUser:true,
  //             columnsUser:list,
  //             user:list[0]
  //           })
  //           return
  //         }else if(data.length == 1){
  //           wx.setStorageSync('userinfo', data[0])
  //         }
  //         let data1 = data[0]
  //         console.log("data.user===>", data1.user)
  //         // 无user表示是劳务工
  //         if (!data1.user) {

  //           let type  = 0;
  //           if(data1.labourCode == null){
  //             type = 1
  //           }
  //           wx.redirectTo({
  //             url: '/pages/firstpage/firstpage?componentType='+type,
  //           })

  //         } else {
  //           console.log("data.user===>", data1.user)
  //           // 有user表示是非劳务工
  //           if (data1.user.typeCode == 'business') {
              
  //             wx.redirectTo({
  //               url: '../companyfirstpage/companyfirstpage',
  //             })
  //           } else if (data1.user.typeCode == 'labour') {
  //             wx.redirectTo({
  //               url: '../laborcompany/firstpage/firstpage',
  //             })
  //           }
  //         }
  //       } else if (res.data.code == 30000) {

  //       } else if (res.data.code == 30002) {

  //       } else {
  //         Toast({
  //           duration: 3000,
  //           forbidClick: true,
  //           type: 'fail',
  //           message: res.data.message,
  //         });
  //       }
  //     },
  //     fail(res) {
  //       Toast.clear();
  //       Toast({
  //         duration: 3000,
  //         forbidClick: true,
  //         type: 'fail',
  //         message: '网络已断开',
  //       });
  //     }
  //   })
  // },
  checkRegister() {
    wx.hideLoading()
    let self = this;
    let openId = wx.getStorageSync("openId");
    let url = `${ApiRootUrl}/index/newCheckUser?openId=${openId}`;
    // Toast.loading({
    //   message: '加载中...',
    //   mask: true,
    //   duration: 0,
    //   forbidClick: true,
    // });
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success(res){
        // Toast.clear();
        wx.hideLoading()
        console.log("res====>111111",res)
        if (res.data.code == 20000) {
        console.log('注册过小程序',res.data.data);
        let userList=res.data.data
        userList.forEach((item)=>{
          if(item.userType==0){
            item.text='待面试-'+item.componentName
          }
          if(item.userType==1){
            item.text='在职务工人员-'+item.componentName
          }
          if(item.userType==2&&item.componentName){
            item.text='在职管理人员-'+item.componentName
          }
          if(item.userType==2&&!item.componentName){
            item.text=item.user.roleName
          }
          if(item.userType==3){
            item.text='离职务工人员-'+item.componentName
          }
          if(item.userType==4){
            item.text='游客'
          }
          if(item.userType==5){
            item.text='外协-'+item.componentName
          }
          if(item.userType==7){
            item.text='未入职申请务工人员-'+item.componentName
          }
        })
        wx.showModal({
          title: '提示',
          content: '您已注册过心园通小程序,请选择角色登录',
          cancelText:"选择角色",
          confirmText:"确定",
          success (res) {
            if (res.confirm) {
              self.setData({
                userList:userList,
                showUserList:true
              })
            } else if (res.cancel) {
              self.setData({
                userList:userList,
                showUserList:true
              })
            }
          }
        })
        } else if (res.data.code == 30000) {

        } else if (res.data.code == 30002) {

        }else if (res.data.code == 30001) {

        } else {
          // Toast({
          //   duration: 3000,
          //   forbidClick: true,
          //   type: 'fail',
          //   message: res.data.message,
          // });
        }
        // Toast.clear();
      },
      fail(res) {
        // Toast.clear();
        wx.hideLoading()
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  getLabourList(code) {
    request(apiList.getLabourList + "?componentCode=" + code, {}, "GET").then(res => {
      let columns = [];
      res.data.forEach((item) => {
        columns.push({
          id: item.orgCode,
          text: item.labourName
        })
      })
      console.log("columns==>",columns,res)
      let obj = {
        id:"",
        text:"全部"
      }
      columns.unshift(obj)
      app.globalData.companyList = columns
      
    }).catch(err => {
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})